package com.lengmomo.games.shiro;

import com.lengmomo.games.pojo.po.User;
import com.lengmomo.games.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.List;

/**
 *
 * @author: lengmomo
 * @create: 2021/8/26
 **/
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    // 告诉shiro如何根据获取到的用户信息中的密码和盐值来校验密码
   /* {
        //设置用于匹配密码的CredentialsMatcher 这里使用Sha256Hash
        HashedCredentialsMatcher hashMatcher = new HashedCredentialsMatcher();
        hashMatcher.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME);
        hashMatcher.setStoredCredentialsHexEncoded(false);
        hashMatcher.setHashIterations(588);
        this.setCredentialsMatcher(hashMatcher);
    }*/

    /**
     * 授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println(LocalDateTime.now()+"执行了授权逻辑");

        return null;
    }

    /**
     * 认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println(LocalDateTime.now()+"执行了认证逻辑");
        //下面是认证（登录）逻辑
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        List<User> users = userService.getUsersByName(token.getUsername());
        if(users == null||users.size()==0){
            throw new UnknownAccountException();//登录名错误
        }else if (users.size()>1){
            //查到多个用户
            throw new RuntimeException();//运行时异常（这里随便加一个吧）
        }
        //接下来这步是校验密码直接return就可以了
        return new SimpleAuthenticationInfo(users.get(0),users.get(0).getPassword(),"");
    }
}
